package config

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"log"
	"strings"
)

type Config struct {
	Name string
}

var v *viper.Viper

func Init() *viper.Viper {
	//cfg := &config.Config{Name: "./config/config.yaml"}
	cfg := &Config{Name: "./config/config.yaml"}
	e := cfg.InitConfig()
	if e != nil {
		fmt.Println(e)
	}
	v = viper.GetViper()
	return v
}
func GetConfig() *Config {
	return &Config{}
}
func V() *viper.Viper {
	if v == nil {
		v = Init()
	}
	return v
}

// viper.SetConfigFile("./config/config.yaml")
// 读取配置
func (c *Config) InitConfig() error {
	if c.Name != "" {
		viper.SetConfigFile(c.Name)
	} else {
		viper.AddConfigPath("config")
		viper.SetConfigName("config")
	}
	viper.SetConfigType("yaml")
	//fmt.Println(c.Name)
	// 从环境变量总读取
	viper.AutomaticEnv()
	viper.SetEnvPrefix("web")
	viper.SetEnvKeyReplacer(strings.NewReplacer("_", "."))
	return viper.ReadInConfig()
}

// 监控配置改动
func (c *Config) WatchConfig(change chan int) {
	viper.WatchConfig()
	viper.OnConfigChange(func(e fsnotify.Event) {
		log.Printf("配置已经被改变: %s", e.Name)
		change <- 1
	})
}
